<?php

class Controller {

	protected $flashdata;
	protected $mailer = null;
	
	
	function mailer() {
		if( $mailer === null ) {
			require_once('lib/swift_init.php');
			$transport = Swift_SmtpTransport::newInstance('mail.crazyhandpuppets.com', 25);;
			$this->mailer = Swift_Mailer::newInstance($transport);			
		}
		return $this->mailer;
	}
	
	function setFlashdata($key, $val) {
		if( !isset( $_SESSION ) ) session_start();
		$this->flashdata['flash_'.$key] = true;
		$_SESSION['flash_' . $key] = $val;
	}
	
	function getFlashdata($key) {
		if( !isset( $_SESSION ) ) session_start();
		return $_SESSION['flash_' . $key];
	}
	
	function keepFlashdata( $key ) {
		$this->flashdata[$key] = true;
	}
	
	function redirect($location) {
		$host = $_SERVER['HTTP_HOST'];
		if( $location{0} !== '/' ) throw new Exception('Could not redirect relative url');
		if( $location === '/' ) header("Location: http://$host/index.php");
		else header("Location: http://$host/index.php/$location");
		// else var_dump("Location: http://$host$location");
		exit;
	}

	function __construct() {
	
	}
	
	function __destruct() {
		// destroy flashdata
		if( isset( $_SESSION ) ) {
			foreach( $_SESSION as $key => $val ) {
				//var_dump( $key, $this->flashdata[$key], !isset( $this->flashdata[$key]  ), (strpos( $key, 'flash_' ) === 0 ) && !isset( $this->flashdata[$key]  )  );
				if( (strpos( $key, 'flash_' ) === 0 )
				&& !isset( $this->flashdata[$key]  ) ) {
					unset( $_SESSION[$key] );
				}				
			}
		}
	}

}
